// pages/cart/cart.js
Page({
  data: {
    cart: [],
    address: {},
    totalNum: 0,
    totalPrice: 0,
    allChecked: false
  },
  /*监听页面加载*/
  onLoad: function (options) {
  },
  onShow: function() {
    const address = wx.getStorageSync('address');
    const cart = wx.getStorageSync('cart') || [];
    this.setCart(cart);
    this.setData({ address })
  },
  // 获取收货地址
  getAddress() {
    wx.getSetting({
      success: result => {
        const scopeAddress = result.authSetting['scope.address.address'];
        if(scopeAddress === true || scopeAddress === undefined) {
          wx.chooseAddress({
            success: (res) => wx.setStorageSync('address', res)
          })
        } else {
          // 用户以前拒绝过授予权限, 应先引导用户打开授权页面
          wx.openSetting({
            success: res => { // 可以调用收获地址代码
              wx.chooseAddress({
                success: (res2) => wx.setStorageSync('address', res2)
              })
            }
          })
        }
      }
    });
  },
  // 监听商品复选框事件
  itemChange(e) {
    // 1. 依goods_id找到它, 并取反checked属性
    const goods_id = e.currentTarget.dataset.id;
    let { cart } = this.data;
    let index = cart.findIndex(v => v.goods_id === goods_id);
    cart[index].checked = !cart[index].checked;
    // 2. 调用函数
    this.setCart(cart);
  },
  // 设置购物车状态, 并重新计算底部工具栏数据
  setCart(cart) {
    // 2. 重新设置data、缓存数据
    wx.setStorageSync('cart', cart);
    // 3. 重新计算全选，总价，总数量
    let allChecked = true;
    let totalNum = 0;
    let totalPrice = 0;
    cart.forEach(v => {
      if(v.checked) {
        totalPrice += v.num * v.goods_price;
        totalNum += v.num;
      } else {
        allChecked = false;
      }
    })
    allChecked = cart.length ? allChecked : false;
    this.setData({ cart, allChecked, totalNum, totalPrice });
  },
  // 商品全选
  allItemChecked() {
    let { cart, allChecked } = this.data;
    allChecked = !allChecked;
    cart.forEach(v => v.checked = allChecked);
    this.setCart(cart);
  },
  // 商品数量变更
  itemNumEdit(e) {
    const { operation, id } = e.currentTarget.dataset;
    let { cart } = this.data;
    let index = -1;
    const item = cart.find((v, i) => {
      index = i;
      return v.goods_id === id;
    });
    // 判断num为1, 且删除情况
    if(item.num === 1 && operation === -1) {
      wx.showModal({
        title: '提示',
        content: '是否需要删除?',
        success: (res) => {
          if (res.confirm) {
            cart.splice(index, 1);
            this.setCart(cart);
          } else if (res.cancel) {
            consoled.log('用户点击了取消');
          }
        }
      })
    } else {
      item && (item.num += operation);
      this.setCart(cart);
    }
  },
  // 结算
  settlement() {
    const { address, totalNum } = this.data;
    if(!address.userName) {
      wx.showToast({
        title: '请先添加收货地址',
        icon: 'success',
        duration: 2000
      })
      return;
    } else if(!totalNum) {
      wx.showToast({
        title: '请先选购商品',
        icon: 'success',
        duration: 2000
      })
      return;
    } else {
      wx.navigateTo({ url: '/pages/pay/pay' })
    }
  }
})
